package user

import (
	"gitee.com/LangHuaHuachihua/blog-go/common"
	"github.com/golang-jwt/jwt/v5"

	"golang.org/x/crypto/bcrypt"
)

type User struct {
	*common.Meta
	*CreateUserRequest
}

func NewDefaultUser() *User {
	return NewUser(NewCreateUserRequest())
}

func NewUser(req *CreateUserRequest) *User {
	return &User{
		Meta:              common.NewMeta(),
		CreateUserRequest: req,
	}
}

func (t *User) HashPassword() error {
	// h := sha1.New()
	// _, err := h.Write([]byte(t.Password))
	// if err != nil {
	// 	return err
	// }
	// data := h.Sum(nil)
	// //base64编码原因  将byte数组转为字符串
	// t.Password = base64.StdEncoding.EncodeToString(data)
	hp, err := bcrypt.GenerateFromPassword([]byte(t.Password), 10)
	if err != nil {
		return err
	}
	t.Password = string(hp)
	return nil
}
func (t *User) CheckPassWord(password string) error {
	err := bcrypt.CompareHashAndPassword([]byte(t.Password), []byte(password))
	if err != nil {
		return err
	}
	return nil
}

func (t *User) TableName() string {
	return "users"
}

func (t *User) String() string {
	return common.Tojson(t)
}

type CreateUserRequest struct {
	Username string `json:"username" validate:"required"`
	Password string `json:"password" validate:"required"`
}

func NewCreateUserRequest() *CreateUserRequest {
	return &CreateUserRequest{}
}

type LoginUserRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func NewLoginUserRequest() *LoginUserRequest {
	return &LoginUserRequest{}
}

func NewDescibeUserRequestByName(name string) *DescibeUserRequest {
	return &DescibeUserRequest{
		DescibeBy:    DESCIBE_BY_NAME,
		DescibeValue: name,
	}
}

type DescibeUserRequest struct {
	DescibeBy    DESCIBE_BY
	DescibeValue string
}

func (t *Token) TableName() string {
	return "tokens"
}

func (t *Token) String() string {
	return common.Tojson(t)
}

type Token struct {
	*common.Meta
	AccessToken string `json:"access_token"`
	Username    string `json:"username"`
}

func NewToken(username string) (*Token, error) {
	token_make := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"meta":     common.NewMeta(),
		"username": username,
	})
	token_str, err := token_make.SigningString()
	if err != nil {
		return nil, err
	}
	// logger.L().Debug().Msgf("user:%s", token_str)
	return &Token{
		Meta:        common.NewMeta(),
		AccessToken: token_str,
		Username:    username,
	}, nil

}

type ValidateToken struct {
	AccessToken string `json:"access_token"`
}

func NewValidateTokenRequest(tk string) *ValidateToken {
	return &ValidateToken{
		AccessToken: tk,
	}
}

// go get github.com/go-playground/validator/v10
func (req *CreateUserRequest) Validate() error {
	//校验规则`  `

	return common.Validate(req)
}
